<?php
namespace Wap\Controller;
use Think\Controller;
use Wap\Controller\WapController;
use Org\Util\Wechat;

/*
 * OrderFood控制器，主要负责微信端用户的逻辑控制
 * _initialize是初始化方法，也是用户每个操作都会处理的
 * 主要是判断用户是否是微信端打开、是否是套餐用户、提示已经取消订单
 * 并获取用户信息$this->wxuserinfo: openid、basketid、colname字段
 */
class OrderFoodController extends WapController {
	public $weObj;
	public $startTime;	// 这期的开始时间
	public $endTime;	// 这期的结束时间, 用于是否在这期中已经点菜过
	
	private $canOrder;
	private $hasOrder;
	
	public $sendTime;
	public $signpackage;

	private $curPeriod;	// 当期的内容, 状态:p_status_go
	private $curGroup;
	private $userQueryPrivilege;
	
	private $wxuserinfo;
	private $basketid;
	public function _initialize() {
		parent::_initialize();
		$self_url = __SELF__;
		$aeq_pos = stripos($self_url, 'a=');
		$op_name = substr($self_url, $aeq_pos+2);
		$this->signpackage = getWXJsSign();
		
		$condition = array('status' => C('p_status_go'));
    	$this->curPeriod = M('period')->where($condition)->find();
    	
    	//获取当前的用户组
    	$this->curGroup = M("group")->where(array('is_use' => 1))->find();
    	
    	$this->wxuserinfo = M('wxuser')->where(array('openid' => session('openid')))->find();
    	
    	$today = date('Y-m-d', time());
    	$this->assign('today', $today);
    	$this->basketid = $this->wxuserinfo['basketid'];
    	$this->assign('basketid', $this->basketid);
    	
    	if(empty($this->wxuserinfo)) {
	    	$this->error('请重新打开!');
	    	exit;
    	}
    	// 判断是否是套餐用户
    	if($this->wxuserinfo['basketid']==0) {
	    	$this->assign('title', "提示");
			$this->assign('msg', "您非套餐用户, 请联系九亩人员!");
			$this->assign('icontype', C('ICON_WAITING'));
			$this->assign('signpackage', $this->signpackage);
			$this->display('info');
			exit;
    	}
    	// 如果已经取消了当期配送，提示用户不可再继续进行点菜
    	if($this->wxuserinfo['cancelorder'] == 1) {
	    	if(strpos($self_url, 'myOrder') == FALSE) {
		    	if (strpos($self_url, 'reOrder') == FALSE) {
			    	$this->assign('title', "提示");
					$this->assign('msg', "您取消了当期配送, 有问题联系九亩人员!");
					$this->assign('icontype', C('ICON_WAITING'));
					$this->assign('signpackage', $this->signpackage);
					$this->assign('url', U("Wap/OrderFood/myOrder"));
					$this->display('info');
					exit;
		    	}	
	    	}
	    	
    	}
	}
	
	/*
	 *	用户点菜首页
	 *	判断用户权限
	 *	根据是否必选 默选，页面根据默选必选情况进行初始化
	 *  套餐菜品的数组结构
	 *  foods = array(
		 ['A'] => array(
			 [sortid-1] => array(
				 [foods] => array(
					 [foodid-1] => array(单个菜品信息),
					 [foodid-2] => array(单个菜品信息),
					 ......
				 },
				 [sort] => array(菜品分类信息),
			 ),
			 ['sortid-2']
		 ),
		 ['B'] => array(
			 
		 ),
	 );
	 */
	public function index() {
		// 检查用户权限,根据具体的action名进行判断
		$chkUsrPrilgRes = checkUserPrivilege();
		if($chkUsrPrilgRes[0]) {
			$this->error($chkUsrPrilgRes[1]);
		}
	
		// 指派orderid，用于判断是否是新订单
		$orderid = I('orderid') ? I('orderid') : 0;
		$this->assign('orderid', $orderid);
		
		$this->isInGroup();
		
		// 检查当前是否在点菜时间内
		$this->timeOKCheck($orderid);
		
		// 点菜界面默认套餐为A
		    $colName = 'A';
		$orderFoods = array();
		// 如果已有订单，说明订单有对应的套餐名,设置
		if($orderid) {
			$ofcondition = array('id' => $orderid, 'opid' => $this->curPeriod['periodid']);
			$order = M('order')->where($ofcondition)->find();
			// 查询订单已点的菜品
			$orderFoods = unserialize($order['ofoods']);
			// 设置显示的套餐名
			$colName = $order['colname'];
		} 

		// 获取到当前所有套餐名称
		$colls = M('period_collocation')->field('colname,colmoney')->group('colname')->select();
		$collnamesArr = array();
		foreach($colls as $coll) {
			$collnamesArr[] = $coll['colname'];
			// 设置默认套餐的价格
			if($colName == $coll['colname']) {
				$colMoney = $coll['colmoney'];
			}
		}
		// 用于界面显示所有的套餐
		$this->assign('collnames', $colls);
		// 指派默认套餐的金额
		$this->assign('colMoneyTotal', $colMoney);
		// 指派默认套餐的名称
		$this->assign('colName', $colName);
		
		// 查询出所有的分类
		$fsorts = M('food_sort')->select();
		
		// 查询出所有套餐的菜品，如果是已有订单，将已点菜品的数量添加到菜品中去
		$foods = array();
		foreach($collnamesArr as $collname) {
			$condition = array();
			// 查询条件： 期数 与 套餐
			$condition['colname'] = $collname;
			$period_collocation_m = M('period_collocation');
			$cbpFoods = $period_collocation_m->join('__PERIOD_COLLOCATION_ITEM__ ON __PERIOD_COLLOCATION__.PCOLID = __PERIOD_COLLOCATION_ITEM__.PC_COLID')->join('__FOOD__ ON __FOOD__.ID = __PERIOD_COLLOCATION_ITEM__.FOODID')->where($condition)->select();
	
			for($i=0; $i<count($cbpFoods); $i++) {
				// 如果已有订单，将数量添加到food中
				if($orderid) {
					foreach($orderFoods as $key => $cvalue) {
						foreach($cvalue as $key1 => $value) {
							if($cbpFoods[$i]['foodid'] == $key1 && $value['ftype'] == 'colfood') {
								$cbpFoods[$i]['orignum'] = $value['num'];
							}
						}
					}
				} else {
					if($cbpFoods[$i]['defchoose'] == 1 && $colName == $collname) {
						$cbpFoods[$i]['orignum'] = 1;
					}
				}
			}
			
			foreach($fsorts as $fsort) {
				foreach($cbpFoods as $food){
					$foodsCreditTotal += $food['cicredit'];
					if($food['sid'] == $fsort['id']) {
						$foods[$collname][$fsort['id']]['foods'][] = $food;
					}
				}
				$foods[$collname][$fsort['id']]['sort'] = $fsort;
			}
		}
		$this->assign('foods', $foods);
		
		// 获取备选菜品
		$opFoodsList = M('period_option_item')->join('__FOOD__ ON __PERIOD_OPTION_ITEM__.FOODID = __FOOD__.ID')->field('tp_period_option_item.id as id, tp_period_option_item.foodid as foodid, tp_food.sid as sid, tp_period_option_item.foodname as foodname, tp_food.price as price, tp_food.instock as instock, tp_food.image as image, 0 as orignum, tp_period_option_item.limit_num as limit_num')->select();
		
		$opFoods = array();
		foreach($fsorts as $fsort) {
			$addSort = false;
			foreach($opFoodsList as $food) {
				foreach($orderFoods as $key => $cvalue) {
					foreach($cvalue as $key1 => $value){
						if($food['foodid'] == $key1 && $value['ftype'] == 'opfood') {
							$food['orignum'] = $value['num'];
						}
					}
				}
				if($food['sid'] == $fsort['id']) {
					$addSort = true;
					$opFoods[$fsort['id']]['foods'][] = $food;
				}
			}
			if($addSort) {
				$opFoods[$fsort['id']]['sort'] = $fsort;
			}
		}
		$this->assign("opFoods", $opFoods);
		
		// 获取另购菜品
		$plusFoodsList = M('period_plus_item')->join('__FOOD__ ON __PERIOD_PLUS_ITEM__.FOODID = __FOOD__.ID')->field('tp_period_plus_item.id as id, tp_period_plus_item.foodid as foodid, tp_food.sid as sid, tp_period_plus_item.foodname as foodname, tp_food.price as price, tp_food.instock as instock, tp_food.image as image, tp_food.unit as unit')->select();
		
		$plusFoods = array();
		foreach($fsorts as $fsort) {
			$addSort = false;
			foreach($plusFoodsList as $food) {
				foreach($orderFoods as $key => $cvalue) {
					foreach($cvalue as $key1 => $value){
						if($food['foodid'] == $key1 && $value['ftype'] == 'plusfood') {
							$food['orignum'] = $value['num'];
						}
					}
				}
				
				if($food['sid'] == $fsort['id']) {
					$addSort = true;
					$plusFoods[$fsort['id']]['foods'][] = $food;
				}
			}
			if($addSort) {
				$plusFoods[$fsort['id']]['sort'] = $fsort;
			}
		}
		$this->assign("plusFoods", $plusFoods);
		
		$this->assign('fsorts', $fsorts);
		$this->assign('maxCount', 6);
		$this->assign('kconoff', 1);
		$this->assign('metaTitle', '菜单');
		$this->assign('basketid', $this->wxuserinfo['basketid']);
		$this->display();
	}
	
	// 确定订单
	public function sureOrder() {
		// 检查用户权限,根据具体的action进行判断
		$chkUsrPrilgRes = checkUserPrivilege();
		if($chkUsrPrilgRes[0]) {
			$this->error($chkUsrPrilgRes[1]);
		}
		// 获取套餐金额 和 套餐菜品实际金额
		$colname = I('colName');
		$colinfo = M('period_collocation')->where(array('colname' => $colname))->find();
		$colMoney = $colinfo['colmoney'];
		
		$colfoods = M('period_collocation_item')->join('__FOOD__ ON __FOOD__.ID = __PERIOD_COLLOCATION_ITEM__.FOODID')->where(array('pc_colid' => $colinfo['pcolid']))->select();
		
		$colMoneyRealCount = 0;
		foreach($colfoods as $food) {
			$colMoneyRealCount += $food['price'];
		}

		// 如果有orderid
		$orderid = I('orderid') ? I('orderid') : 0;
		$this->assign('orderid', $orderid);
		if($orderid) {
			$order = M('order')->where(array('id' => $orderid))->find();
		}
		$this->assign('order', $order);
		
		$this->timeOKCheck($orderid);
		$nums = 0;
		$foods = array();
		$colopMoneyCount = 0;
		$plusMoneyCount = 0;
		$isCal = false;	// 是否计算过超过套餐金额这种情况
		foreach($_POST['foods'] as $k1 => $cfood) {
			foreach($cfood as $key => $food) {
				// 获取菜品信息
				$tmpfood = M('food')->where(array('id'=>$key))->find();
				$fnum = $food['num'];
				$ftype = $food['ftype'];
				$fprice = $tmpfood['price'];
				// 有数量的才是真正需要的数据
				if($fnum != null && $fnum > 0) {
					// 如果菜品采购数量超过库存 & 备选区，提示信息
					if($fnum > $tmpfood['instock'] && ($ftype == 'opfood' || $ftype == 'plusfood')) {
						$this->assign('title', "提示");
						$this->assign('msg', "您采购的".$food['name']."超过了库存量，有人捷足先登了哦！");
						$this->assign('icontype', C('ICON_WAITING'));
						$this->assign('signpackage', $this->signpackage);
						$this->display('info');
						exit;
					}
					
					$nums += $fnum;
					$foods[$k1][$key] = $food;
					$foods[$k1][$key]['image'] = $tmpfood['image'];
					$foods[$k1][$key]['unit']  = $tmpfood['unit'];
					
					// 相关数量 金额计算
					if($ftype == 'colfood' || $ftype == 'opfood') {
						$colopMoneyCount += $fnum * $fprice;
					}else if($ftype == 'plusfood') {
						$plusMoneyCount += $fnum * $fprice;
					}
				} 
			}
		}
		// 汇总计算
		//$colopMoneyCount = $colopMoneyCount - ($colMoneyRealCount - $colMoney);
		$extraMoneyCount = floor($colopMoneyCount) + $plusMoneyCount - $colMoney;
		
		$this->assign('orderid', $_POST['orderid']);
		$this->assign('foods', $foods);
		$this->assign('colname', $colname);
		
		$this->assign('nums', $nums);
		$this->assign('colopMoneyCount', $colopMoneyCount);
		$this->assign('plusMoneyCount', $plusMoneyCount);
		$this->assign('extraMoneyCount', $extraMoneyCount);
		
		$discount_money = $this->wxuserinfo['discount_money'];
		$this->assign('discount_money', $discount_money);

		$this->assign('sendTime', $this->sendTime);
		$this->assign('metaTitle', '确认订单');
		$this->assign('curPeriodId', $this->curPeriod['periodid']);
		$this->display();
	}
	
	// 提交订单	
	public function submitOrder() {
		// 检查用户权限,根据具体的action进行判断
		$chkUsrPrilgRes = checkUserPrivilege();
		if($chkUsrPrilgRes[0]) {
			$this->error($chkUsrPrilgRes[1]);
		}
		
		// 如果有orderid
		$orderid = I('orderid') ? I('orderid') : 0;
		$this->assign('orderid', $orderid);
		
		$this->timeOKCheck($orderid);

		// 处理订单前，更新库存
		foreach($_POST['foods'] as $cfood) {
			foreach($cfood as $key => $food) {
				$ftype = $food['ftype'];
				if($ftype == 'opfood' || $ftype == 'plusfood') {
					$condition = array('id' => $key);
					$thisfood = M('food')->where($condition)->find();
					$instock = $thisfood['instock'] - $food['num'];
					$data = array('instock' => $instock);
					M('food')->where($condition)->save($data);
				}
			}
		}
		// 处理订单到数据库
		$oid 		= time().substr(microtime(),2,6).rand(0,9);
		$opid		= $_POST['opid'];
		$ofoods 	= serialize($_POST['foods']);
		$colname 	= I('colname');
		$state 		= C('UNSEND');	// 0 未发货 1 已发货 2 用户已收货
		$istmsg 	= 0; 	// 0 未发送 已发货模板消息
		$mark		= $_POST['omark'];
		$addtime 	= time();
		$odata = array(
			'oid'		=> $oid,
			'opid'		=> $opid,
			'openid'	=> $this->openid,
			'basketid'	=> $this->basketid,
			'colname'	=> $colname,
			'ofoods'	=> $ofoods,
			'state'		=> $state,	// 未发货
			'autoOrder'	=> 0,		// ordertype:(0:手工 1:自动 2:取消订单)
			'istmsg'	=> $istmsg,
			'mark'		=> $mark,
			'addtime'	=> $addtime,
			'sendtime'	=> ''
		);
		if($orderid) {
			$condition = array('id' => $orderid);
			$addRes = M('order')->where($condition)->save($odata);
		} else {
			$addRes = M('order')->add($odata);
		}
		 
		$this->assign('title', '提示');
		$this->assign('url', U("Wap/OrderFood/myOrder"));
		$this->assign('msg', '订单提交成功！静候佳肴！');
		$this->assign('icontype', C('ICON_SUCCESS'));
		$this->assign('signpackage', $this->signpackage);
		
		$username = $_POST['ouserName'];
		$address  = $_POST['ouserAddres'];
		$usersex  = $_POST['ouserSex'];
		$tel	  = $_POST['ouserTel'];
		$pdata = array("address" => $address, "tell" => $tel, "truename" => $username, "psex" => $usersex);
		$condition = array("openid" => $this->openid);
		\Think\Log::write("用户（".$this->openid."）创建菜单");
		// 更新收货地址
		$updatePostRes = M('wxuser')->where($condition)->save($pdata);
		
		$totalnum = trim($_POST['totalnum']);
		
		// 点菜界面默认套餐为A
		$colName = 'A';
		// 获取到当前所有套餐名称
		$colls = M('period_collocation')->field('colname,colmoney')->group('colname')->select();
		foreach($colls as $coll) {
			// 设置默认套餐的价格
			if($colName == $coll['colname']) {
				$colMoney = $coll['colmoney'];
			}
		}

		
		// 获取此次订单的超出金额
		$extraMoneyCount = I("extraMoneyCount");
		$extraMoneyCountStr = '套餐内消费';
		if($extraMoneyCount>0) {
			$extraMoneyCountStr = '￥'.($extraMoneyCount + $colMoney);
		}
		// 有订单号表示是修改
		if($orderid) {
			$data = array("touser"=>"$this->openid",
						"template_id"=>"4e_1ebW7M6iYe2dOrJ-TzXpdwcFnN-J_HMkpGIQTcZ0",
						"url"=> C('site_url').U('Wap/OrderFood/myOrder'),
						"topcolor"=>"#FF0000",
						"data"=> array( "first"=>array("value"=>"本期九亩公社点菜修改成功", "color"=>"#173177"), 
									"keyword1" =>array("value"=>"$oid", "color"=>"#173177"),
									"keyword2" =>array("value"=>"$username", "color"=>"#173177"),
									"keyword3" =>array("value"=>"$address", "color"=>"#173177"),
									"keyword4" =>array("value"=>$extraMoneyCountStr, "color"=>"#173177"),
									"keyword5" =>array("value"=>"$this->sendTime", "color"=>"#173177"),
									"remark"   =>array("value"=>"一共".$totalnum."份，将尽快送达！", "color"=>"#173177"),
						)
			);
		} else {
			$data = array("touser"=>"$this->openid",
						"template_id"=>"4e_1ebW7M6iYe2dOrJ-TzXpdwcFnN-J_HMkpGIQTcZ0",
						"url"=> C('site_url').U('Wap/OrderFood/myOrder'),
						"topcolor"=>"#FF0000",
						"data"=> array( "first"=>array("value"=>"本期九亩公社点菜提交成功", "color"=>"#173177"), 
									"keyword1" =>array("value"=>"$oid", "color"=>"#173177"),
									"keyword2" =>array("value"=>"$username", "color"=>"#173177"),
									"keyword3" =>array("value"=>"$address", "color"=>"#173177"),
									"keyword4" =>array("value"=>$extraMoneyCountStr, "color"=>"#173177"),
									"keyword5" =>array("value"=>"$this->sendTime", "color"=>"#173177"),
									"remark"   =>array("value"=>"一共".$totalnum."份，将尽快送达！", "color"=>"#173177"),
						)
			);
		}
		
		$weObj = new Wechat();
		$msg_result = $weObj->sendTemplateMessage($data);
		$this->display('info');
	}
	
	// 用户点击取消订单
	public function cancelOrder() {
		$openid = session('openid');
		
		$cond_1 = array('openid' => $openid);
		$data_1 = array('cancelorder' => 1);
		$res = M('wxuser')->where($cond_1)->save($data_1);
		
		$this->assign('title', "提示");
		$this->assign('msg', "您已成功取消当期配送!");
		$this->assign('icontype', C('ICON_SUCCESS'));
		$this->assign('signpackage', $this->signpackage);
		\Think\Log::write("用户（".$openid."）取消菜单");
		$this->display('info');
	}
	
	// 展示我的订单
	public function myOrder() {
		// 检查用户权限,根据具体的action进行判断
		$chkUsrPrilgRes = checkUserPrivilege();
		if($chkUsrPrilgRes[0]) {
			$this->error($chkUsrPrilgRes[1]);
		}
		
		$this->chkPeriodTime();
		$condition = "tp_order.openid = '$this->openid'";
		$orderList =  M('order')->field('*,tp_order.id as orderid, tp_wxuser.id as wxuserid, tp_order.opid as oopid')->join('__WXUSER__ ON __ORDER__.OPENID = __WXUSER__.OPENID')->where($condition)->order('addtime desc')->select();
		//\Think\Log::write("我的订单 =》" . dump($orderList, false));
		foreach($orderList as $key => $order) {
			$order['postTime'] = $this->getSendTime($order['addtime']);
			$order['info'] = unserialize($order['ofoods']);
			$foodsTotal = 0;
			foreach($order['info'] as $cfood) {
				foreach($cfood as $food) {
					$foodsTotal += $food['num'];
				}
			}
			$order['foodTotal'] = $foodsTotal;
			$orderList[$key] = $order;
		}
		
		$this->assign('basketid', $this->wxuserinfo['basketid']);
		$this->assign('orderList', $orderList);
		$this->assign('curPeriodid', $this->curPeriod['periodid']);
		\Think\Log::write("当前期数 =》" . dump($this->curPeriod, false));
		
		$this->assign('canOrder', $this->canOrder);
		$this->assign('metaTitle', '订单详情');
		// 获取用户当前订单的状态（是否取消）
		$cancel_status = $this->wxuserinfo['cancelorder'];
		$this->assign('cancel_status', $cancel_status);
		
		$this->display();
	}
	
	// 重新下单，即用户修改为 （取消 取消订单）
	public function reOrder() {
		$openid = $this->wxuserinfo['openid'];
		$res = M('wxuser')->where(array('openid' => $openid))->save(array('cancelorder' => 0));

		$this->assign('title', "提示");
		$this->assign('msg', "您修改重新下单状态成功!");
		$this->assign('icontype', C('ICON_SUCCESS'));
		$this->assign('signpackage', $this->signpackage);
		$this->assign('url', U("Wap/OrderFood/index"));
		$this->display('info');
	}
	
	// 更新用户地址
	public function updateAddress() {
		$openid = I('openid');
		$truename = I('username');
		$tell = I('tel');
		$psex = I('sex');
		$address = I('addr');
		
		$condition = array('openid' => $openid);
		$data = array(
			'truename' 	=> $truename,
			'tell'		=> $tell,
			'psex'		=> $psex,
			'address'	=> $address
		);
		M('wxuser')->where($condition)->save($data);
		// 暂不做返回
	}
	
    /*
     *  送货员展示当期订单界面，用于check是否配送到
     */
    public function deliverOrder() {
    	// 检查用户权限,根据具体的action进行判断
		$chkUsrPrilgRes = checkUserPrivilege();
		if($chkUsrPrilgRes[0]) {
			$this->assign('title', "提示");
			$this->assign('icontype', C('ICON_WAITING'));
			$this->assign('msg', $chkUsrPrilgRes[1]);
			$this->assign('url', U('Wap/OrderFood/myOrder'));
			$this->assign('signpackage', $this->signpackage);
			$this->display('info');
			exit;
		}
		
		// 查询出刚关闭的一期
		$condition_1['doGeneral'] = array('eq', 1);
		$condition_1['status'] = array('eq', 3);
		$lastPeriod = M('period')->where($condition_1)->order('endtime desc')->limit(1)->select();
        $period = $lastPeriod[0]['periodid'];
        $condition_2 = array('opid' => $period);
        $orderList = M('order')->join('__WXUSER__ ON __ORDER__.OPENID = __WXUSER__.OPENID')->where($condition_2)->select();
        
        $this->assign('orderList', $orderList);
        $this->display();
    }
    
    public function doDeliver() {
	    $orderid = I('orderid');
		$condition_1 = array('oid' => $orderid);
		$mark = I('delivermark');
		$data_1 = array('state' => '3', 'delivermark' => $mark);
		
		// 检查用户权限,根据具体的action进行判断
		$chkUsrPrilgRes = checkUserPrivilege(null, $data_1);
		if($chkUsrPrilgRes[0]) {
			$this->assign('title', "提示");
			$this->assign('icontype', C('ICON_WAITING'));
			$this->assign('msg', $chkUsrPrilgRes[1]);
			$this->assign('url', U('Wap/OrderFood/deliverOrder'));
			$this->assign('signpackage', $this->signpackage);
			$this->display('info');
			exit;
		}
		$res_1 = M('order')->where($condition_1)->save($data_1);
		if($res_1) {
			$this->assign('title', "提示");
			$this->assign('icontype', C('ICON_SUCCESS'));
			$this->assign('msg', "订单状态修改成功!");
			$this->assign('url', U('Wap/OrderFood/deliverOrder'));
			$this->assign('signpackage', $this->signpackage);
			
			$condition_2 = array("oid" => $orderid);
			$orderinfo = M('order')->join("__WXUSER__ ON __ORDER__.OPENID = __WXUSER__.OPENID")->join("__PERIOD__ ON __ORDER__.OPID = __PERIOD__.PERIODID")->where($condition_2)->find();
			
			// 配送成功，微信模板消息提醒
			$first = "尊贵的九亩客户，您第".$orderinfo['pname']."期选购的九亩套餐已送达！";
			$keyword1 = "祝您生活愉快！";
			$time = date("Y-m-d H:i", time());
			$data = array("touser"=>$orderinfo['openid'],
						"template_id"=>"msCBRvXMNr6YR2_0FQVrqvH0B8PSH7O9ijS5DNBcAXM",
						"url"=> '',
						"topcolor"=>"#FF0000",
						"data"=> array( "first"=>array("value"=>$first, "color"=>"#173177"), 
									"keyword1" =>array("value"=>$keyword1, "color"=>"#173177"),
									"keyword2" =>array("value"=>"$time", "color"=>"#173177"),
									"remark"   =>array("value"=>"绿色饮食, 健康人生!", "color"=>"#173177"),
						)
			);
			$weObj = new Wechat();
			$msg_result = $weObj->sendTemplateMessage($data);
			// 标识订单的 istmsg为1，表示已向用户发送了配送结果模板消息
			if($msg_result) {
				$condition_3 = array("opid" => $orderid);
				$data_3 = array("istmsg" => 1);
				M('order')->where($condition_3)->save($data_3);
			}
			$this->display('info');
		} else {
			$this->assign('title', "提示");
			$this->assign('icontype', C('ICON_WAITING'));
			$this->assign('msg', "订单状态修改失败!");
			$this->assign('url', U('Wap/OrderFood/deliverOrder'));
			$this->assign('signpackage', $this->signpackage);
			$this->display('info');
		}
    }
	public function getSendTime($time) {
		$d = date('w', $time);
		switch($d) {
			case 0:
				return '下周一配送';
				break;
			case 1:
				return '当周四配送';
				break;
			case 2:
				return '当周四配送';
				break;
			case 3:
				return '当周四配送';
				break;
			case 4:
				return '下周一配送';
				break;
			case 5:
				return '下周一配送';
				break;
			case 6:
				return '下周一配送';
				break;
		}
	}
	
	// 检查是否是点菜的时间段
	public function chkSendTime() {
		$d = date('w');
		switch($d) {
			case 0:
				$this->canOrder = true;		//$this->chkAM();
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec - (36*3600);
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周一开始配送";
				break;
			case 1:
				$this->canOrder = true;
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec;
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周四开始配送";
				break;
			case 2:
				$this->canOrder = true;
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec - (24*3600);
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周四开始配送";
				break;
			case 3:
				$this->canOrder = true;		//$this->chkAM();
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec - (48*3600);
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周四开始配送";
				break;
			case 4:
				$this->canOrder = true;
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec;
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周一开始配送";
				break;
			case 5:
				$this->canOrder = true;
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec - (24*3600);
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周一开始配送";
				break;
			case 6:
				$this->canOrder = true;
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec - (48*3600);
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周一开始配送";
				break;
		}
	}
	/*
	public function chkSendTime() {
		$d = date('w');
		switch($d) {
			case 0:
				$this->canOrder = $this->chkAM();
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec - (24*3600);
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周一开始配送";
				break;
			case 1:
				$this->canOrder = false;
				break;
			case 2:
				$this->canOrder = true;
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec;
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周四开始配送";
				break;
			case 3:
				$this->canOrder = $this->chkAM();
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec - (24*3600);
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周四开始配送";
				break;
			case 4:
				$this->canOrder = false;
				break;
			case 5:
				$this->canOrder = false;
				break;
			case 6:
				$this->canOrder = true;
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec;
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周一开始配送";
				break;
		}
	}*/
	
	// 判断是否是上午
	public function chkAM() {
		$today = date("Y-m-d");
		$zero_clock_sec  = strtotime($today);
		$now_clock_sec   = time(date("Y-m-d"));
		if ($now_clock_sec < $zero_clock_sec + (24*3600)) {	// change
			return true;
		}else {
			return false;
		}
	}
	
	// 判断是否已经订餐
	public function hasOrder() {
		$condition = array();
		$condition['opid'] 	= $this->curPeriod['periodid'];
		$condition['openid'] 	= $this->openid;
		
		$res = M('order')->where($condition)->select();
		if(empty($res)) {
			return false;
		} else {
			return true;
		}
	}
	
	/*
	 * 检查是否在这期时间内
	 */
	private function chkPeriodTime() {
		$now_clock_sec   = time(date("Y-m-d"));	// 当前时间
		$fromtime = $this->curPeriod['fromtime'];
		$endtime = $this->curPeriod['endtime'];
		if($now_clock_sec > $fromtime && $now_clock_sec < $endtime) {
			$this->canOrder = true;
		} else {
			$this->canOrder = false;
		}
	}
	/*
	 * 检查是否有状态:go 的期数
	 * 检查是否在这期时间内
	 */
	public function timeOKCheck($orderid = null) {
		// 如果没有状态:go的期数, 提示稍等
		$this->chkPeriodTime();
		// 这期已经go，但是没在时间区间内
		if(!$this->curPeriod || !$this->canOrder) {
			$this->assign('title', "提示");
			$this->assign('url', U("Wap/OrderFood/myOrder"));
			$this->assign('msg', "这期点菜还未开始或者不在点菜时间, 请稍等!");
			$this->assign('icontype', C('ICON_WAITING'));
			$this->assign('signpackage', $this->signpackage);
			$this->display('info');
			exit();
		}
		// 提示是否您已点菜:有订单，且无订单id
		if($this->hasOrder() && empty($orderid)) {
			// 如果有orderid参数，表示修改订单
			$this->assign('title', "提示");
			$this->assign('url', U("Wap/OrderFood/myOrder"));
			$this->assign('icontype', C('ICON_SUCCESS'));
			$this->assign('msg', "本期您已点菜");
			$this->assign('signpackage', $this->signpackage);
			$this->display('info');
			exit();
		}
	}
	
	/*
	 *	检查你能点菜
	 */
	public function isInGroup() {
		$condition_0 = array('openid' => $this->openid, "gid" => $this->curGroup['id']);
		$user = M('user_group')->where($condition_0)->find();
		if(empty($user)) {
			$this->assign('title', "提示");
			$this->assign('url', U('Wap/OrderFood/myOrder'));
			$this->assign('icontype', C('ICON_SUCCESS'));
			$this->assign('msg', "您不在当期的用户组中,想加入请联系客服.");
			$this->assign('signpackage', $this->signpackage);
			$this->display('info');
			exit;
		} 
	}
}
?>